package com.papercutting.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.papercutting.platform.entity.News;
import com.papercutting.platform.repository.NewsRepository;
import com.papercutting.platform.service.NewsService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 活动资讯服务实现类
 */
@Service
public class NewsServiceImpl implements NewsService {
    
    private final NewsRepository newsRepository;
    
    public NewsServiceImpl(NewsRepository newsRepository) {
        this.newsRepository = newsRepository;
    }
    
    @Override
    public News save(News news) {
        if (news.getId() == null) {
            newsRepository.insert(news);
        } else {
            newsRepository.updateById(news);
        }
        return news;
    }

    @Override
    public News findById(Long id) {
        return newsRepository.selectById(id);
    }

    @Override
    public List<News> findAll() {
        return newsRepository.selectList(null);
    }

    @Override
    public Page<News> findAll(Pageable pageable) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<News> page =
            new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(
                pageable.getPageNumber() + 1, pageable.getPageSize());
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<News> result =
            newsRepository.selectPage(page, null);
        return new PageImpl<>(result.getRecords(), pageable, result.getTotal());
    }

    @Override
    public void deleteById(Long id) {
        newsRepository.deleteById(id);
    }

    @Override
    public List<News> findByType(Integer type) {
        QueryWrapper<News> wrapper = new QueryWrapper<>();
        wrapper.eq("type", type);
        return newsRepository.selectList(wrapper);
    }

    @Override
    public List<News> findByIsRecommend(Boolean isRecommend) {
        QueryWrapper<News> wrapper = new QueryWrapper<>();
        wrapper.eq("is_recommend", isRecommend);
        return newsRepository.selectList(wrapper);
    }

    @Override
    public List<News> findByIsTop(Boolean isTop) {
        QueryWrapper<News> wrapper = new QueryWrapper<>();
        wrapper.eq("is_top", isTop);
        return newsRepository.selectList(wrapper);
    }

    @Override
    public List<News> findByStatus(Integer status) {
        QueryWrapper<News> wrapper = new QueryWrapper<>();
        wrapper.eq("status", status);
        return newsRepository.selectList(wrapper);
    }

    @Override
    public List<News> findByTitleContaining(String title) {
        QueryWrapper<News> wrapper = new QueryWrapper<>();
        wrapper.like("title", title);
        return newsRepository.selectList(wrapper);
    }
    
    @Override
    public void increaseViewCount(Long id) {
        News news = findById(id);
        if (news != null) {
            news.setViewCount(news.getViewCount() + 1);
            save(news);
        }
    }
    
    @Override
    public Page<News> findNewsList(Integer type, String keyword, Integer status, Pageable pageable) {
        List<News> allNews = findAll();
        
        // 根据类型筛选
        if (type != null) {
            allNews = allNews.stream()
                .filter(news -> type.equals(news.getType()))
                .collect(Collectors.toList());
        }
        
        // 根据状态筛选 - 默认只查询已发布的内容（status=1），除非明确指定了status参数
        if (status != null) {
            allNews = allNews.stream()
                .filter(news -> status.equals(news.getStatus()))
                .collect(Collectors.toList());
        } else {
            allNews = allNews.stream()
                .filter(news -> Integer.valueOf(1).equals(news.getStatus()))
                .collect(Collectors.toList());
        }
        
        // 根据关键词搜索
        if (keyword != null && !keyword.isEmpty()) {
            allNews = allNews.stream()
                .filter(news -> 
                    (news.getTitle() != null && news.getTitle().contains(keyword)) ||
                    (news.getSummary() != null && news.getSummary().contains(keyword))
                )
                .collect(Collectors.toList());
        }
        
        // 分页处理
        int start = (int) pageable.getOffset();
        int end = Math.min(start + pageable.getPageSize(), allNews.size());
        List<News> pageContent = start <= end && start < allNews.size() ? 
            allNews.subList(start, end) : List.of();
            
        return new PageImpl<>(pageContent, pageable, allNews.size());
    }
}